package com.zc.service.impl;

import com.zc.base.ResponseResult;
import com.zc.component.RedisCache;
import com.zc.pojo.LoginUser;
import com.zc.pojo.User;
import com.zc.service.LoginService;
import com.zc.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @description:
 * @author: cong
 * @create: 2024/8/2
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;
    /**
     * 用户登录方法
     *
     * @param user 用户对象，包含用户名和密码
     * @return 返回登录结果，包含状态码、消息和数据
     */
    @Override
    public ResponseResult login(User user) {
        // 创建用户名和密码令牌
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 进行用户认证
        Authentication authenticate = authenticationManager.authenticate(token);

        // 检查认证结果
        if (Objects.isNull(authenticate)) {
            // 认证失败
            return new ResponseResult<>(500, "登录失败", null);
        }
        // 认证成功，生成JWT令牌并存储用户信息到Redis
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJwt(userId);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        redisCache.setCacheObject(userId, loginUser);
        // 返回登录成功结果，包含状态码、消息和JWT令牌
        return new ResponseResult<>(200, "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String id = loginUser.getUser().getId().toString();
            boolean result = redisCache.deleteObject(id);
            if (result) {
                return new ResponseResult<>(200, "退出成功", null);
            }
        }
        return null;
    }

}
